﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using PLCS.Domain.Logs;
using PLCS.SocialHttpApi.Attributes;
using System.ComponentModel;
using System.Text.Json;
using Volo.Abp.Domain.Repositories;

namespace PLCS.SocialHttpApi;

public class LogActionFilter : IActionFilter
{
    private readonly IRepository<InterfaceLog, Guid> _repository;

    public LogActionFilter(IRepository<InterfaceLog, Guid> repository)
    {
        _repository = repository;
    }

    public void OnActionExecuting(ActionExecutingContext context)
    {
        // 获取控制器名称
        var controllerName = context.RouteData.Values["controller"].ToString();

        // 获取Action方法名称
        var actionName = context.RouteData.Values["action"].ToString();

        // 获取请求参数信息
        var parametersJson = JsonSerializer.Serialize(context.ActionArguments);

        // 获取正在执行的Action方法
        var actionDescriptor = context.ActionDescriptor;

        // 获取Action方法上的指定特性
        var descriptionAttribute = actionDescriptor.EndpointMetadata.OfType<DescriptionAttribute>().FirstOrDefault();
        var requesterAttribute = actionDescriptor.EndpointMetadata.OfType<RequesterAttribute>().FirstOrDefault();
        var descriptor = descriptionAttribute?.Description ?? string.Empty;
        var requester = requesterAttribute?.Value ?? string.Empty;

        var log = new InterfaceLog(requester, "PLCS", actionName, descriptor, Domain.Shared.Logs.InterfaceMode.WebApi, Domain.Shared.Logs.InterfaceDataType.Json, parametersJson, "");
        context.HttpContext.Items["RequestLog"] = log;
    }

    public void OnActionExecuted(ActionExecutedContext context)
    {
        // 获取日志对象
        var log = (InterfaceLog)context.HttpContext.Items["RequestLog"];

        if (context.Result != null)
            // 获取返回结果
            log.ResponseData = JsonSerializer.Serialize(((ObjectResult)context.Result).Value);

        _repository.InsertAsync(log);
    }
}